package com.mti.monitor.service;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 发送短信工具类
 */
@Service
@Log4j2
public class MessageService {

	/**
	 * 发送预警短信
	 * @param phoneNums 短信电话
	 * @param messageContent 短信内容
	 */
    public void sendAlarmMessage(String phoneNums,String messageContent,String messageChannel)
    {
		//todo messageChannel短信发送通道，目前只有昆明公安。暂不处理
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair = new BasicNameValuePair("username", "rlgj");
		NameValuePair pair2 = new BasicNameValuePair("password", "rlgj110");
		NameValuePair pair3 = new BasicNameValuePair("destAddr", phoneNums);
		NameValuePair pair4 = new BasicNameValuePair("content", messageContent);
		params.add(pair);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);
		String retStr = null;
		try
		{
			//发送短信
			retStr = postWithParamsForString("http://86.84.147.46:8110/api/http/SendSmsMessage", params);
		}
		catch (Exception ex)
		{
			log.error("sendMessageUrl retStr error ========================= {}" , ex.getMessage());
		}
		log.info("sendMessageUrl retStr ========================= {}" , retStr);
    }


	/**
	 * 短信发送接口
	 * @param url
	 * @param params
	 * @return
	 */
	private  String postWithParamsForString(String url, List<NameValuePair> params){
		HttpClient client = HttpClients.createDefault();
		HttpPost httpPost =   new HttpPost(url);
		String retStr = "";
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode==200){
				HttpEntity entity = response.getEntity();
				retStr = EntityUtils.toString(entity);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return retStr;
	}

}
